/*
 * Created on 2004-6-22
 */
package com.geng.utils;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


/**
 * @author geng
 * 验证码工具类
 */
public class ImageUtils
{
    public static void genValidateCode(HttpServletRequest req,
        HttpServletResponse res)
    {
        String strValidateCode = genRandomNumStr(4);
        HttpSession session = req.getSession(true);
        session.setAttribute("validateCode", strValidateCode);

        res.reset();
        res.setHeader("Pragma", "No-cache");
        res.setHeader("Cache-Control", "no-cache");
        res.setDateHeader("Expires", 0);

        try
        {
            int width = 48;
            int height = 18;
            BufferedImage image = new BufferedImage(width, height,
                    BufferedImage.TYPE_INT_RGB);
            Graphics g = image.getGraphics();

            //设置图片为白色背景的方框
            g.setColor(Color.white);
            g.fillRect(0, 0, width, height);
            
            //设置图片边框为黑色
            g.setColor(Color.black);
            g.drawRect(0, 0, width - 1, height - 1);
            
            //设置字体颜色
            g.setColor(Color.red);
            g.setFont(new Font("Times New Roman", Font.PLAIN, 18));
            g.drawString(strValidateCode, 6, 15);

            //设置干扰线数目及颜色
            Random random = new Random();
            int x = 0 ;
            int y = 0;
            g.setColor(Color.CYAN);
            for (int i = 0; i < 48; i++)
            {
                x = random.nextInt(width);
                y = random.nextInt(height);
                g.drawLine(x, y, x, y);
            }

            g.dispose();

            ImageIO.write(image, "JPEG", res.getOutputStream());
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    public static String genRandomNumStr(int intLength)
    {
        char[] c = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
        Random random = new Random();
        StringBuffer sb = new StringBuffer();

        for (int i = 0; i < intLength; i++)
        {
            sb.append(c[random.nextInt(10)]);
        }

        return sb.toString();
    }
    
    public static void genQR(HttpServletRequest req,
            HttpServletResponse res,BufferedImage bm)
        {
            try{

                ImageIO.write(bm, "JPEG", res.getOutputStream());
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
}
